<template>
  <h2>一个人的信息</h2>
  <h3>姓名：{{name}}</h3>
  <h3>年龄：{{age}}</h3>
  <h3>薪资：{{salary}}k</h3>
  <button @click="name += '~'">修改姓名</button>
  <button @click="age++">增加年龄</button>
  <button @click="salary++">加薪</button>
</template>

<script>
import { reactive, toRef, toRefs } from 'vue';
export default {
  name: 'Demo', 
  setup() {
    let person = reactive({
        name: '张三',
        age: 18,
        job: {
            j1: {
                salary: 20, 
            }
        }
    })

    //为了减防止模板中写大量person.，返回数据时直接取属性返回
    //错误写法，name/age/salary不是响应式数据，只是基本类型数据
    /*
    return {
        name: person.name,
        age: person.age,
        salary: person.job.j1.salary,
    }
    */
    console.log('toRef', toRef(person, 'name'))
    //正确写法1，toRef将对象中的某个属性变成RefImpl类型，name/age/salary会引用RefImpl，修改name时实际修改person.name
    /*
    return {
      name: toRef(person, 'name'),
      age: toRef(person, 'age'),
      salary: toRef(person.job.j1, 'salary')
    }
    */
   console.log('toRefs', toRefs(person))
    //正确写法2，toRefs将一个对象中所有属性创建为RefImpl类型，无需指定属性
    return {
      salary: toRef(person.job.j1, 'salary'),
      ...toRefs(person),
    }
  }
}
</script>

<style>
</style>